let Socket = ''
let setIntervalWebsocketPush = null

export const createSocket = (url)=>{
    Socket && Socket.close()
    if (!Socket){
        Socket = new WebSocket(url)
        Socket.onmessage = onmessageWS
        Socket.onerror = onerrorWS
        Socket.onclose = oncloseWS
    }
}

const openWS= ()=>{
    sendPing()
}

const onerrorWS = ()=>{
    Socket.close()
    clearInterval(setIntervalWebsocketPush)
    console.log("与服务器重连中")
    if (Socket.readyState!==3){
        Socket = null
        createSocket()
    }
}
const onmessageWS = e => {
    window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
            data: e.data
        }
    }))
}

const connecting = message => {
    setTimeout(() => {
        if (Socket.readyState === 0) {
            connecting(message)
        } else {
            Socket.send(JSON.stringify(message))
        }
    }, 1000)
}

export const sendWSPush = message => {
    if (Socket !== null && Socket.readyState === 3) {
        Socket.close()
        createSocket()
    } else if (Socket.readyState === 1) {
        Socket.send(JSON.stringify(message))
    } else if (Socket.readyState === 0) {
        connecting(message)
    }
}

const oncloseWS = () => {
    clearInterval(setIntervalWebsocketPush)
    console.log('websocket已断开....正在尝试重连')
    if (Socket.readyState !== 2) {
        Socket = null
        createSocket()
    }
}

export const sendPing = (time = 5000, ping = 'ping') => {
    clearInterval(setIntervalWebsocketPush)
    Socket.send(ping)
    setIntervalWebsocketPush = setInterval(() => {
        Socket.send(ping)
    }, time)
}